package com.fqgame.user.controller;

import com.fqgame.common.core.domain.R;
import com.fqgame.user.service.AsyncTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 异步任务控制器
 */
@RestController
@RequestMapping("/async")
public class AsyncTaskController {

    @Autowired
    private AsyncTaskService asyncTaskService;

    /**
     * 执行异步任务
     */
    @GetMapping("/task")
    public R<String> executeAsyncTask(@RequestParam("taskName") String taskName) {
        asyncTaskService.executeAsyncTask(taskName);
        return R.ok("异步任务已提交执行");
    }

    /**
     * 处理文件（异步）
     */
    @GetMapping("/file")
    public R<String> processFile(@RequestParam("fileName") String fileName) {
        CompletableFuture<String> future = asyncTaskService.processFileAsync(fileName);
        // 不等待结果，直接返回
        return R.ok("文件处理任务已提交，文件名：" + fileName);
    }

    /**
     * 处理文件（同步等待结果）
     */
    @GetMapping("/file/wait")
    public R<String> processFileAndWait(@RequestParam("fileName") String fileName) {
        try {
            CompletableFuture<String> future = asyncTaskService.processFileAsync(fileName);
            // 等待异步任务完成并获取结果
            String result = future.get();
            return R.ok(result);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return R.fail("文件处理被中断");
        } catch (ExecutionException e) {
            return R.fail("文件处理失败: " + e.getCause().getMessage());
        }
    }

    /**
     * 处理数据（同步）
     */
    @GetMapping("/data")
    public R<String> processData(@RequestParam("data") String data) {
        String result = asyncTaskService.processData(data);
        return R.ok(result);
    }
}